package com.leorui.schoollife.utils

import okhttp3.*
import java.io.IOException

class OkHttpUtils {
    private var okHttpClient: OkHttpClient? = null
    var callback: IntelCallback? = null

    fun init() {
        okHttpClient = OkHttpClient()
    }

    fun postAsync(url: String) {
        val request = Request.Builder().url(url).get().build()
        okHttpClient?.newCall(request)?.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback?.onError(e.message)
            }

            override fun onResponse(call: Call, response: Response) {
                callback?.onResponse(response.body?.string())
            }
        })
    }

    fun postExecute(url: String) {
        val request = Request.Builder().url(url).get().build()
        try {
            val response = okHttpClient?.newCall(request)?.execute()
            callback?.onResponse(response?.body?.string())
        } catch (e: Exception) {
            callback?.onError(e.message)
        }
    }

    interface IntelCallback {
        fun onError(msg: String?)
        fun onResponse(html: String?)
    }
}